package com.medica.ledproject;

import onbon.y2.Y2Env;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

@SpringBootApplication
public class LedProjectApplication implements ApplicationContextAware {
    private static ApplicationContext applicationContext;
    private static DefaultListableBeanFactory defaultListableBeanFactory;
    public static void main(String[] args) {
        // 初始化API，此操作只在程序启动时候执行一次，多次执行会出现内存错误
        Y2Env.initial();
        SpringApplication.run(LedProjectApplication.class, args);
       // System.out.println(getRootDirectory());
    }
    public static String getRootDirectory(){
        return  System.getProperty("user.dir");
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
        defaultListableBeanFactory = (DefaultListableBeanFactory)applicationContext.getAutowireCapableBeanFactory();
    }

    public static <T> T getBean(Class<T> clazz) {
        BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(clazz);
        String className = clazz.getName();
        defaultListableBeanFactory.registerBeanDefinition(className, beanDefinitionBuilder.getBeanDefinition());
        return (T) applicationContext.getBean(className);
    }

    public static void destroy(String className){
        defaultListableBeanFactory.removeBeanDefinition(className);
        System.out.println("destroy " + className);
    }
}
